package com.kevin.service.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kevin.service.entity.SysMessageTo;
import com.kevin.service.mapper.SysMessageMapper;
import com.kevin.service.entity.SysMessage;
import com.kevin.service.service.SysMessageService;
import com.kevin.service.service.SysMessageToService;
import com.kevin.service.util.SseEmitterUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 消息表(SysMessage)表服务实现类
 *
 * @author makejava
 * @since 2023-12-08 16:14:34
 */
@Service
@RequiredArgsConstructor
public class SysMessageServiceImpl extends ServiceImpl<SysMessageMapper, SysMessage> implements SysMessageService {
    private final SysMessageToService messageToService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveP(SysMessage entity) {
        save(entity);
        List<Long> userIdList = entity.getUserIdList();
        messageToService.saveBatch(userIdList.stream().map(userId ->
                        SysMessageTo.builder()
                                .messageId(entity.getId())
                                .receiver(userId)
                                .readed(false)
                                .build())
                .collect(Collectors.toList()));

        SseEmitterUtils.batchSendMessage("【" + entity.getTitle() + "】" + entity.getContent(), userIdList.stream().map(String::valueOf).collect(Collectors.toSet()));

    }
}

